package com.example.sharding.algorithm;

import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Date;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.*;

@Slf4j
public class MonthShardingAlgorithm implements ComplexKeysShardingAlgorithm<Date> {

    private static final String DATE_COLUMN = "create_time"; // 你的日期字段名

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
                                         ComplexKeysShardingValue<Date> shardingValue) {
        Set<String> result = new LinkedHashSet<>();

        // 获取分片键的值
        Map<String, Collection<Date>> columnShardingValues = shardingValue.getColumnNameAndShardingValuesMap();

        Map<String, Range<Date>> columnNameAndRangeValuesMap = shardingValue.getColumnNameAndRangeValuesMap();

        // 如果没有分片键值，返回所有表
        if ((columnShardingValues.isEmpty() || !columnShardingValues.containsKey(DATE_COLUMN))
                && (columnNameAndRangeValuesMap.isEmpty() || !columnNameAndRangeValuesMap.containsKey(DATE_COLUMN)))
        {
            return availableTargetNames;
        }

        if(columnNameAndRangeValuesMap.containsKey(DATE_COLUMN)) {
            Range<Date> range = columnNameAndRangeValuesMap.get(DATE_COLUMN);
            // 处理范围查询
            if (range != null && (range.hasLowerBound() || range.hasUpperBound())) {
                Date startDate = new Date();
                Date endDate = new Date();

                if(range.hasLowerBound()) {
                    startDate = (Date) range.lowerEndpoint();
                }

                if(range.hasUpperBound()) {
                    endDate = (Date) range.upperEndpoint();
                }

                Calendar start = Calendar.getInstance();
                start.setTime(startDate);
                Calendar end = Calendar.getInstance();
                end.setTime(endDate);

                // 遍历从 start 到 end 的每一个“月”
                while (!start.after(end)) {
                    int year = start.get(Calendar.YEAR);
                    int month = start.get(Calendar.MONTH) + 1;

                    String tableSuffix = String.format("_%04d%02d", year, month);

                    for (String tableName : availableTargetNames) {
                        if (tableName.endsWith(tableSuffix)) {
                            result.add(tableName);
                            break;
                        }
                    }

                    // 前进到下一个月
                    start.add(Calendar.MONTH, 1);
                }
            }
        }
        else if(columnShardingValues.containsKey(DATE_COLUMN)) {
            Collection<Date> dates = columnShardingValues.get(DATE_COLUMN);
            // 为每个日期值确定表名
            for (Date date : dates) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始

                // 格式化为表后缀，如_202301
                String tableSuffix = String.format("_%04d%02d", year, month);

                // 匹配对应的表
                for (String tableName : availableTargetNames) {
                    if (tableName.endsWith(tableSuffix)) {
                        result.add(tableName);
                        break;
                    }
                }
            }
        }

        log.info("匹配到的表为：{}", result);

        // 如果表不存在，则创建
//        if (!availableTargetNames.contains(tableName)) {
//            createTableIfNotExists(tableName);
//        }

        return result.isEmpty() ? availableTargetNames : result;
    }

    @Override
    public Properties getProps() {
        return new Properties();
    }

    @Override
    public void init(Properties props) {
        // 初始化逻辑
        log.info("MonthShardingAlgorithm init");
    }

    @Override
    public String getType() {
        return "MONTH_SHARDING";
    }

    public void createTableIfNotExists(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        String tableName = String.format("order_%04d%02d", year, month);

        // 检查表是否存在，不存在则创建
        if (!tableExists(tableName)) {
            String sql = String.format("CREATE TABLE %s LIKE order_template", tableName);
            // 执行SQL创建表
            //jdbcTemplate.execute(sql);
        }
    }

    private boolean tableExists(String tableName) {
        // 实现检查表是否存在的逻辑
        return false;
    }
}

